[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)][string]$ExtractedSources,
    [Parameter(Mandatory=$true)][string]$ManifestIn,
    [Parameter(Mandatory=$true)][string]$ManifestOut,
    [Parameter(Mandatory=$true)][string]$CMakeFragmentFile,
    [Parameter(Mandatory=$false)][string]$vcpkg = "vcpkg"
)

$ErrorActionPreference = "Stop"

$subfolders = Get-Item $ExtractedSources\aws-cpp-sdk-*

$manifest = Get-Content $ManifestIn | ConvertFrom-Json
$manifest | Add-Member -NotePropertyName 'features' -NotePropertyValue @{}

$cmakefragmenttext = @("# Automatically generated by generateFeatures.ps1")

function GetDescription($dir, $modulename)
{
    if (Test-Path "$dir\CMakeLists.txt")
    {
        $descs = @(Select-String -Path "$dir\CMakeLists.txt" -Pattern "`"C\+\+ SDK for the AWS [^`"]*`"")
        if ($descs.count -eq 1) {
            $desc = $descs[0].Matches.Value -replace "`"",""
            "$desc"
        }
        else { "C++ SDK for the AWS $modulename service" }
    }
    else { "C++ SDK for the AWS $modulename service" }
}

foreach ($subfolder in $subfolders)
{
    $modulename = $subfolder.name -replace "^aws-cpp-sdk-",""
    if ($modulename -match "-tests`$") { continue }
    if ($modulename -match "-sample`$") { continue }
    if ($modulename -eq "core") { continue }

    $lowermodulename = $modulename.ToLower()

    $manifest.features.Add("$lowermodulename", @{ description=(GetDescription $subfolder $modulename) })

    $cmakefragmenttext += @(
        "if(`"$lowermodulename`" IN_LIST FEATURES)",
        "  list(APPEND BUILD_ONLY $modulename)",
        "endif()"
    )
}

[IO.File]::WriteAllText($ManifestOut, (ConvertTo-Json -Depth 5 -InputObject $manifest))

Write-Verbose ($cmakefragmenttext -join "`n")
[IO.File]::WriteAllText($CMakeFragmentFile, ($cmakefragmenttext -join "`n") +"`n")

vcpkg format-manifest --feature-flags=-manifests $ManifestOut
